package com.androidmtk;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/** Nested class that performs the restart */
public class RestartRunnable implements Runnable {
	Handler mHandler;
	private String restartName;
	private String restartCommand;
	private String restartResponse;

	RestartRunnable(Handler h, int mode) {
		mHandler = h;

		String restartName;
		String restartCommand;
		String restartResponse;
		switch (mode) {
		case 1:
			restartName = "Hot start";
			restartCommand = "PMTK101";
			restartResponse = "PMTK010,001";
			break;
		case 2:
			restartName = "Warm start";
			restartCommand = "PMTK102";
			restartResponse = "PMTK010,001";
			break;
		case 3:
			restartName = "Cold start";
			restartCommand = "PMTK103";
			restartResponse = "PMTK010,001";
			break;
		default:
			sendTOAST("Unrecognized restart mode");
			return;
		}

		this.restartName = restartName;
		this.restartCommand = restartCommand;
		this.restartResponse = restartResponse;
	}

	public void run() {
		
		Log.v(AndroidMTK.TAG, "+++ ON " + restartName + " +++");
			
		GPSrxtx gpsdev = new GPSrxtx(AndroidMTK.getmBluetoothAdapter(),
				AndroidMTK.getGPS_bluetooth_id());
		Message msg = mHandler.obtainMessage();
		if (gpsdev.connect()) {
			// Send the command to perform restart
			try {
				gpsdev.sendCommand(restartCommand);
				// Wait for reply from the device
				gpsdev.waitForReply(restartResponse);
			} catch (BluetoothException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			gpsdev.close();
			msg.obj = restartName + " succeed";
		} else
			msg.obj = restartName + " failed";

		mHandler.sendMessage(msg);
		Log.d(AndroidMTK.TAG, "++++ Done: " + restartName);
	}

	/**
	 * @param message 
	 */
	private void sendTOAST(String message) {

		Message msg = mHandler.obtainMessage();
		Bundle b = new Bundle();
		b.putString(AndroidMTK.KEY_TOAST, message);
		msg.setData(b);

		mHandler.sendMessage(msg);
	}
}
